const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const path = require('path');
const PDFDocument = require('pdfkit');

// 模拟数据库
const BACKTESTS_FILE = path.join(__dirname, '../data/backtests.json');

// 确保数据目录存在
const ensureDataDirExists = () => {
  const dataDir = path.join(__dirname, '../data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
  }
};

// 初始化回测数据
const initBacktests = () => {
  ensureDataDirExists();
  if (!fs.existsSync(BACKTESTS_FILE)) {
    fs.writeFileSync(BACKTESTS_FILE, JSON.stringify([]));
  }
};

// 获取所有回测记录
exports.getBacktests = () => {
  initBacktests();
  const data = fs.readFileSync(BACKTESTS_FILE, 'utf8');
  return JSON.parse(data);
};

// 根据ID获取回测结果
exports.getBacktestById = (id) => {
  const backtests = exports.getBacktests();
  return backtests.find(backtest => backtest.id === id);
};

// 保存回测结果
exports.saveBacktestResult = (backtestResult) => {
  initBacktests();
  const backtests = exports.getBacktests();
  const newBacktest = {
    ...backtestResult,
    id: backtestResult.id || uuidv4(),
    createdAt: new Date().toISOString()
  };
  backtests.push(newBacktest);
  fs.writeFileSync(BACKTESTS_FILE, JSON.stringify(backtests, null, 2));
  return newBacktest;
};

// 创建回测
exports.createBacktest = async (backtestData) => {
  // 调用策略服务进行回测
  const strategyService = require('./strategy');
  const backtestResult = await strategyService.backtestStrategy(
    backtestData.strategyId,
    backtestData
  );
  return backtestResult;
};

// 导出回测报告
exports.exportBacktestReport = (id) => {
  const backtest = exports.getBacktestById(id);
  if (!backtest) throw new Error('回测记录不存在');

  // 创建临时文件路径
  const tempDir = path.join(__dirname, '../temp');
  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir);
  }
  const reportPath = path.join(tempDir, `backtest_report_${id}.pdf`);

  // 创建PDF文档
  const doc = new PDFDocument();
  doc.pipe(fs.createWriteStream(reportPath));

  // 添加报告标题
  doc.fontSize(20).text('回测报告', { align: 'center' });
  doc.moveDown();

  // 添加策略信息
  doc.fontSize(16).text('策略信息', { underline: true });
  doc.moveDown();
  doc.fontSize(12).text(`策略ID: ${backtest.strategyId}`);
  doc.text(`回测ID: ${backtest.id}`);
  doc.text(`开始时间: ${new Date(backtest.startTime).toLocaleString()}`);
  doc.text(`结束时间: ${new Date(backtest.endTime).toLocaleString()}`);
  doc.moveDown();

  // 添加回测结果摘要
  doc.fontSize(16).text('回测结果摘要', { underline: true });
  doc.moveDown();
  doc.fontSize(12).text(`初始资金: ${backtest.initialBalance}`);
  doc.text(`最终资金: ${backtest.finalBalance.toFixed(2)}`);
  doc.text(`总收益: ${backtest.totalProfit.toFixed(2)}`);
  doc.text(`收益率: ${backtest.profitRate}%`);
  doc.text(`最大回撤: ${backtest.maxDrawdown.toFixed(2)}%`);
  doc.text(`胜率: ${backtest.winRate.toFixed(2)}%`);
  doc.text(`总交易次数: ${backtest.totalTrades}`);
  doc.text(`盈利交易次数: ${backtest.winningTrades}`);
  doc.text(`亏损交易次数: ${backtest.losingTrades}`);
  doc.moveDown();

  // 添加免责声明
  doc.fontSize(10).text('免责声明: 本回测报告仅供参考，不构成任何投资建议。', { italic: true });

  // 结束文档
  doc.end();

  return reportPath;
};